package com.pojocreator.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pojocreator.common.AccessProperties;
import com.pojocreator.dto.TableDTO;

public class TableExplorer {
	
	private static final Log log = LogFactory.getLog(TableExplorer.class);
	
	private Connection connection;
	public TableExplorer(ConnectionManager connectionManager){
		this.connection=connectionManager.getConnection();
	}
	public List<TableDTO> getAllTableDescription(){
		HashMap<String, String> tableMap=new HashMap<String, String>();
		
		List<TableDTO> tablesList=new ArrayList<TableDTO>();
		
		String sql=AccessProperties.getValueFromProps("db.Query");
		PreparedStatement pstmt = null;
		
		try {
			pstmt = connection.prepareStatement(sql);
			//pstmt.setString(1,tableName);
			ResultSet rs = pstmt.executeQuery();
			
			String prevTabName=null;
			String curTabName=null;

			int count=0;
			TableDTO tempDto=new TableDTO();
			
			while(rs.next()){
				if(count==0){
					prevTabName=rs.getString("TABLE_NAME");// Set the table name for the first row
					tempDto.setTableName(prevTabName);
					count++;
				}
				curTabName=rs.getString("TABLE_NAME"); // Get the table name for the current row
				if(curTabName.equalsIgnoreCase(prevTabName)){
					tableMap.put(rs.getString("COLUMN_NAME"),rs.getString("DATA_TYPE"));
				}else {
					tempDto.setRowToDataTypeMap(tableMap);
					log.debug(tempDto);
					tablesList.add(tempDto);
					tempDto=new TableDTO();
					tempDto.setTableName(curTabName);
					tableMap=new HashMap<String, String>(); //Fresh column map for new table
					prevTabName=curTabName;
					//count=0; // Fresh count for next table
					tableMap.put(rs.getString("COLUMN_NAME"),rs.getString("DATA_TYPE"));
				}
			}
			//Setting the last table details
			log.debug("last Row");
			tempDto.setRowToDataTypeMap(tableMap);
			log.debug(tempDto);
			tablesList.add(tempDto);
		} catch (SQLException e) {
			log.error("",e);
		}
		return tablesList;
	}
}
